package com.jz.netthings.analysis.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.jz.netthings.analysis.bean.ProviderRound;
import com.jz.netthings.analysis.bean.RoundsBase;
import com.jz.netthings.analysis.mapper.ProviderRoundMapper;
import com.jz.netthings.analysis.mapper.RoundsBaseMapper;
import com.jz.netthings.analysis.service.ProviderRoundService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.jz.netthings.appengine.baseData.ProviderInfo;
import com.jz.netthings.appengine.mapper.ProviderInfoMapper;
import com.jz.netthings.application.providerCollection.bean.DonatorException;
import com.jz.netthings.application.providerCollection.bean.ProviderCollection;
import com.jz.netthings.application.providerCollection.mapper.mysql.DonatorExceptionMapper;
import com.jz.netthings.application.providerCollection.mapper.mysql.ProviderCollectionMapper;
import com.jz.netthings.application.providerReg.bean.ProviderReg;
import com.jz.netthings.application.providerReg.mapper.mysql.ProviderRegMapper;
import com.jz.netthings.bloodsources.bean.XyFiveLink;
import com.jz.netthings.bloodsources.mapper.XyFiveLinkMapper;
import com.jz.netthings.exception.AdscmSystemException;
import com.jz.netthings.utils.AdscmBaseUtils;
import com.jz.netthings.utils.AdscmDateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 供浆者轮次 服务实现类
 * </p>
 *
 * @author yangyunyun
 * @since 2019-07-16
 */
@Service
public class ProviderRoundServiceImpl extends ServiceImpl<ProviderRoundMapper, ProviderRound> implements ProviderRoundService {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    ProviderInfoMapper providerInfoMapper;
    @Autowired
    ProviderRegMapper providerRegMapper;
    @Autowired
    RoundsBaseMapper roundsBaseMapper;
    @Autowired
    ProviderRoundMapper providerRoundMapper;
    @Autowired
    ProviderCollectionMapper providerCollectionMapper;
    @Autowired
    DonatorExceptionMapper donatorExceptionMapper;
    @Autowired
    XyFiveLinkMapper xyFiveLinkMapper;

    @Override
    public ProviderRound loadProviderRound(Long providerId, int year) throws AdscmSystemException {

        logger.info("构造供浆者["+providerId+"]["+year+"]年的所有轮次数据...");

        ProviderRound round = new ProviderRound(false);
        round.setProviderId(providerId);
        round.setYear(year);
        round = providerRoundMapper.selectOne(round);
        boolean isInsert = false;
        if (round == null){
            isInsert = true;
            round = new ProviderRound(true);
            round.setProviderId(providerId);
            round.setYear(year);
        }

        //构造轮次数据，格式如下：
        //1：日期      正常
        //2：日期      临床反应
        //3：日期：链接护士名字 	  采浆日期 == 链接日期 && 正常
        //4：日期：链接护士名字 	  采浆日期 == 链接日期 && 临床反应
        //5：日期      R浆员

        //卡号
        String cardId = this.getCardId(providerId);


        String beginTime = year + "-01-01 00:00:00";
        String endTime = year + "-12-31 23:59:59";

        List<ProviderCollection> collections = this.getCollections(providerId,beginTime,endTime);
        if (collections != null && collections.size()>0){
            for (ProviderCollection collection : collections) {
                this.setProviderRound(collection,cardId,round);
            }
        }

        if (isInsert){
            providerRoundMapper.insert(round);
        }else {
            providerRoundMapper.updateById(round);
        }
        return round;
    }

    @Override
    public void loadProviderRound(int year) throws AdscmSystemException{
        logger.info("构造所有供浆者["+year+"]年的所有轮次数据...");
        Wrapper<ProviderInfo> wrapper = new EntityWrapper<>();
        wrapper.orderBy("id",false);
        List<ProviderInfo> infoList = providerInfoMapper.selectList(wrapper);
        for (ProviderInfo info : infoList) {
            this.loadProviderRound(info.getId(),year);
        }
    }


    private void setProviderRound(ProviderCollection collection,String cardId,ProviderRound round){

        Date collDate = collection.getCollectionDate();
        String collDateStr = AdscmDateUtils.getDateFormat(collDate);
        //采浆的轮次
        RoundsBase roundsBase = roundsBaseMapper.selectRoundsByDate(collDateStr);

        if(cardId.startsWith("R")){
            round.setRound(roundsBase.getRoundIdx()+"","5:"+collDateStr);
        }else {
            //临床反应
            boolean hasException = false;
            String mLogId = collection.getMachineLogId();
            if (AdscmBaseUtils.getInstance().isNotEmpty(mLogId,null)){
                Wrapper<DonatorException> exceWrapper = new EntityWrapper<>();
                exceWrapper.eq("mlogId",mLogId);
                int exCount = donatorExceptionMapper.selectCount(exceWrapper);
                if (exCount > 0){
                    hasException = true;
                }
            }

            //五步链接，后面再加
            boolean isFiveLink = false;
            String linkNurseName = "";//链接护士名字
            //查询五步链接.....
            Wrapper<XyFiveLink> fiveLinkWrapper = new EntityWrapper<>();
            fiveLinkWrapper.eq("linkProviderId",collection.getProviderNo());
            fiveLinkWrapper.between("linkTime",collDateStr + " 00:00:00 ",collDateStr + " 23:59:59 ");
            List<XyFiveLink> xyFiveLinks = xyFiveLinkMapper.selectList(fiveLinkWrapper);
            if(AdscmBaseUtils.getInstance().listIsNotEmpty(xyFiveLinks)){
                isFiveLink = true;
                StringBuffer temp = new StringBuffer();
                for (int i = 0;i<xyFiveLinks.size();i++) {
                    XyFiveLink fiveLink = xyFiveLinks.get(i);
                    temp.append(fiveLink.getProviderName());
                    if(i < (xyFiveLinks.size() - 1)){
                        temp.append("，");
                    }
                }
                linkNurseName = temp.toString();
            }


            if (isFiveLink){
                if(hasException){
                    round.setRound(roundsBase.getRoundIdx()+"","4:"+collDateStr+":"+linkNurseName);
                }else {
                    round.setRound(roundsBase.getRoundIdx()+"","3:"+collDateStr+":"+linkNurseName);
                }
            }else {
                if(hasException){
                    round.setRound(roundsBase.getRoundIdx()+"","2:"+collDateStr);
                }else {
                    round.setRound(roundsBase.getRoundIdx()+"","1:"+collDateStr);
                }
            }

        }
    }

    private List<ProviderCollection> getCollections(Long providerId,String beginTime,String endTime){
        Wrapper<ProviderCollection> collWrapper = new EntityWrapper<>();
        collWrapper.eq("providerNo",providerId);
        collWrapper.eq("isDeal",1);
        collWrapper.gt("totalPlasmaNum",590);
        collWrapper.between("collectionDate",beginTime,endTime);
        collWrapper.orderBy("collectionDate",true);
        List<ProviderCollection> collections = providerCollectionMapper.selectList(collWrapper);
        return collections;
    }


    private String getCardId(Long providerId)throws AdscmSystemException{
        ProviderInfo info = providerInfoMapper.selectById(providerId);
        if (info == null){
            throw new AdscmSystemException("没有查到["+providerId+"]对应的浆员信息");
        }
        //卡号
        return info.getCardId();
    }

    @Override
    public void loadProviderRoundByDate(Long providerId, String date) throws AdscmSystemException{
        logger.info("构造供浆者["+providerId+"]在["+date+"]献浆的轮次数据...");
        int year = AdscmDateUtils.getTheYear(AdscmDateUtils.parseDate(date));
        ProviderRound round = new ProviderRound(false);
        round.setProviderId(providerId);
        round.setYear(year);
        round = providerRoundMapper.selectOne(round);
        boolean isInsert = false;
        if (round == null){
            isInsert = true;
            round = new ProviderRound(true);
            round.setProviderId(providerId);
            round.setYear(year);
        }


        //卡号
        String cardId = this.getCardId(providerId);

        String beginTime = date + " 00:00:00";
        String endTime = date + " 23:59:59";

        List<ProviderCollection> collections = this.getCollections(providerId,beginTime,endTime);
        if (collections != null && collections.size()>0){
            ProviderCollection collection = collections.get(0);
            this.setProviderRound(collection,cardId,round);
        }

        if (isInsert){
            providerRoundMapper.insert(round);
        }else {
            providerRoundMapper.updateById(round);
        }
    }

    @Override
    public void loadRegProviderRound(String regDate)throws AdscmSystemException {

        if (!AdscmBaseUtils.getInstance().isNotEmpty(regDate,null)){
            regDate = AdscmDateUtils.getNowOnlyDateFomat1(new Date());
        }

        logger.info("构造在["+regDate+"]登记的供浆者献浆的轮次数据...");

        String beginTime = regDate + " 00:00:00";
        String endTime = regDate + " 23:59:59";

        Wrapper<ProviderReg> wrapper = new EntityWrapper<>();
        wrapper.between("regTime",beginTime,endTime);
        List<ProviderReg> regList = providerRegMapper.selectList(wrapper);
        if (regList != null && regList.size()>0){
            for (ProviderReg providerReg : regList) {
                this.loadProviderRoundByDate(Long.parseLong(providerReg.getProviderNo()),regDate);
            }
        }
    }
}
